package pe.gob.sunat.editors;

import java.beans.PropertyEditorSupport;


import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.factory.annotation.Configurable;

import pe.gob.sunat.domain.Vehiculo;
import pe.gob.sunat.service.VehiculoService;

@Configurable
public class VehiculoEditor extends PropertyEditorSupport {
	
	private SimpleTypeConverter typeConverter = new SimpleTypeConverter();
	
	private VehiculoService vehiculoService;

	public VehiculoEditor(VehiculoService vehiculoService) {
		super();
		this.vehiculoService = vehiculoService;
	}
	
	public String getAsText() {
		Object obj = getValue();
		if (obj == null) {
			return null;
		}
		return (String) typeConverter.convertIfNecessary(((Vehiculo) obj).getNumSerieMotor(), String.class);
	}

	public void setAsText(String text) {
		if (text == null || "".equals(text)) {
			setValue(null);
			return;
		}

		String identifier = (String) typeConverter.convertIfNecessary(text, String.class);
		
		if (identifier == null) {
			setValue(null);
			return;
		}

		setValue(vehiculoService.find(identifier));
	}

}
